package com.deyou.util;

import android.util.Base64;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

/**
 * Created by yangyuancheng on 2017/5/25.
 */

public class AESUtil {

    private static String key="lianghuilonglong";
    private static SecretKey secretKey;
    private static final String AES = "AES";

    static {
        try {
            secretKey = new SecretKeySpec(key.getBytes(), AES);
        } catch (Exception ex) {
        }
    }

    public static byte[] hexToBytes(String hexString) {
        if (hexString == null || hexString.equals("")) {
            return null;
        }

        int length = hexString.length() / 2;
        char[] hexChars = hexString.toCharArray();
        byte[] bytes = new byte[length];
        String hexDigits = "0123456789abcdef";
        for (int i = 0; i < length; i++) {
            int pos = i * 2; // 两个字符对应一个byte
            int h = hexDigits.indexOf(hexChars[pos]) << 4; // 注1
            int l = hexDigits.indexOf(hexChars[pos + 1]); // 注2
            if(h == -1 || l == -1) { // 非16进制字符
                return null;
            }
            bytes[i] = (byte) (h | l);
        }
        return bytes;
    }

    /**
     * 加密
     *
     * @param data 待加密数据
     * @return
     * @throws Exception
     */
    public static String encrypt(String data)  {
        byte[] endata;
        String a="";
        try {
            endata = encrypt(data.getBytes());
            a=Base64.encodeToString(endata, Base64.CRLF);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return a;
    }

    /**
     * 解密
     *
     * @param data 待解密数据
     * @return
     * @throws Exception
     */
    public static String decrypt(String data)  {
        byte be[] = Base64.decode(data, Base64.CRLF);
        try {
            return new String(decrypt(be));
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }

    private static byte[] encrypt(byte[] data) throws Exception {
        if (null == secretKey) {
            throw new SecurityException("secretKey is null");
        }
        Cipher cipher = Cipher.getInstance(secretKey.getAlgorithm());
        cipher.init(Cipher.ENCRYPT_MODE, secretKey);
        return cipher.doFinal(data);
    }

    private static byte[] decrypt(byte[] data) throws Exception {
        if (null == secretKey) {
            throw new SecurityException("secretKey is null");
        }
        Cipher cipher = Cipher.getInstance(secretKey.getAlgorithm());
        cipher.init(Cipher.DECRYPT_MODE, secretKey);
        return cipher.doFinal(data);
    }
}
